<?php


namespace common\services;


use yii\db\ActiveQuery;
use yii\db\Query;

/**
 * 获取分页数据
 * Class PageService
 * @package common\services
 */
class PageService
{
    /**
     * 获取分页数据
     * @param Query $query
     * @param int $limit
     * @return array
     */
    public static function getPage(Query $query, $limit = 20, $page = null)
    {
        if ($page === null) {
            $request = \Yii::$app->request;
            $page = $request->get('page') ?: $request->post('page');
        }
        $page = $page ?? 1;
        $offset = ($page - 1) * $limit;
        $count = $query->count();

        $query = $query->offset($offset)->limit($limit);

        # ActiveQuery extends Query | ActiveQuery use ActiveQueryTrait 支持asArray
        if ($query instanceof ActiveQuery) $query = $query->asArray();

        return [
            'total' => intval($count),
            'current_page' => intval($page),
            'page_total' => intval(ceil($count / $limit)),
            'data' => $query->all()
        ];
    }


    /**
     * 计算分页数据
     * @param Query $query
     * @param int $limit
     * @return array
     */
    public static function calculationPage($total, $limit = 20, $page = null)
    {
        if ($page === null) {
            $request = \Yii::$app->request;
            $page = $request->get('page') ?: $request->post('page');
        }
        $page = $page ?? 1;
        $offset = ($page - 1) * $limit;

        return [
            'offset' => intval($offset),
            'current_page' => intval($page),
            'page_total' => intval(ceil($total / $limit)),
        ];
    }


}